import { Http } from "../network/http";
import { TornaReply } from "../types/type";
export namespace TornaHttp {
  export async function fetch<
    R,
    P extends unknown = any,
    J extends unknown = any
  >(
    url: string,
    options?: Http.IFetchOpts<P, J>
  ): Promise<TornaReply<R>> {
    const reply = await Http.fetch(url, options).then(v => v.json<TornaReply<R>>());
    if (reply.code !== '0') {
      throw new Error(`url: [${reply.code}] ${reply.msg}`);
    }
    return reply;
  }
  export interface IGet<R extends unknown = any, H extends Http.Headers = Http.Headers, S extends unknown = any> {
    (
      url: string,
      headers: H,
      search: S,
      canceller?: AbortController
    ): Promise<R>
  }
  export const get: IGet = async <R extends unknown = any, H extends Http.Headers = Http.Headers, S extends unknown = any>(
    url: string,
    headers: H,
    search: S | undefined,
    canceller?: AbortController
  ) => {
    const r = await TornaHttp.fetch<R>(url, { headers, search, method: 'GET', ...canceller });
    return r.data;
  };
}